package edu.stanford.prpl.common.util;

import org.apache.log4j.Logger;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;

/**
 * HashUtils <p/> Code based off example from <a
 * href="http://www.anyexample.com/programming/java/java_simple_class_to_compute_sha_1_hash.xml">here</a>.
 * 
 * @author brigham (on Feb 4, 2008 at 4:09:28 PM)
 */
public class HashUtils {

	private static Logger log = Logger.getLogger("edu.stanford.sal.prpl.impl.HashUtils");

	/**
	 * sseong-HashUtils.fileToSha1 fixed on Aug 4, 2008
	 */
	public static String fileToSHA1(File file) {
		FileInputStream inputStream = null;
		try {
			MessageDigest md = MessageDigest.getInstance("SHA-1");
			inputStream = new FileInputStream(file);
			md.update(file.getName().getBytes());
			byte[] dataBytes = new byte[4096];
			int nread = inputStream.read(dataBytes);
			while (nread > 0) {
				md.update(dataBytes, 0, nread);
				nread = inputStream.read(dataBytes);
			}
			byte[] mdbytes = md.digest();
			return convertToHex(mdbytes);
		} catch (Exception e) {
			log.error("Error retrieving SHA-1 of file <" + file + ">", e);
			return null;
		} finally {
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException e) {
				}
			}
		}
	}

	public static String StringToSHA1(String s) {
		try {
			MessageDigest md = MessageDigest.getInstance("SHA-1");
			md.update(s.getBytes());
			byte[] mdbytes = md.digest();
			return convertToHex(mdbytes);
		} catch (Exception e) {
			log.error("Error retrieving SHA-1 of String <" + s + ">", e);
			return null;
		}
	}

	private static String convertToHex(byte[] data) {
		StringBuffer buf = new StringBuffer();
		for (byte b : data) {
			int halfbyte = (b >>> 4) & 0x0F;
			int two_halfs = 0;
			do {
				if ((0 <= halfbyte) && (halfbyte <= 9))
					buf.append((char) ('0' + halfbyte));
				else
					buf.append((char) ('a' + (halfbyte - 10)));
				halfbyte = b & 0x0F;
			} while (two_halfs++ < 1);
		}
		return buf.toString();
	}

}
